import { smsCode, Login, getInfo, loginOut } from '@/api/user'
import { getToken, setToken, removeToken, getMgrSn, setMgrSn, removeMgrSn } from '@/utils/auth'
import md5 from "js-md5";

const getDefaultState = () => {
  return {
    token: getToken(),
    mgrSn: getMgrSn(),
    mobile: "",
    roles: []
  }
}

const state = getDefaultState()

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_MGRSN: (state, mgrSn) => {
    state.mgrSn = mgrSn
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  //退出登录重置state
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
    window.location.reload()
  },
}



const actions = {
  // get user info
  getSmsCode({ commit, state }, { mobile, smsType }) {
    return new Promise((resolve, reject) => {
      smsCode({ mobile: mobile.trim(), smsType: smsType }).then(response => {
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },
  login({ commit, state }, { mobile, pwd, smsCode }) {
    return new Promise((resolve, reject) => {
      Login({ mobile: mobile.trim(), pwd: md5(pwd), smsCode: smsCode }).then(response => {
        if (response.data.resultStatus) {
          const { mgrSn, token } = response.data.resultData
          commit('SET_TOKEN', token)
          commit('SET_MGRSN', mgrSn)
          setToken(token)
          setMgrSn(mgrSn)
        }
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo({ mgrSn: state.mgrSn }).then(response => {
        if (response.data.resultStatus) {
          var data = ['admin']
          const { roleId, userName } = response.data.resultData
          commit('SET_ROLES', [roleId])
          resolve(data)
        }
      }).catch(error => {
        reject(error)
      })
    })
  },
  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      console.log({token:state.token})
      loginOut({token:state.token}).then(() => {
        removeToken() // must remove  token  first
        removeMgrSn()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      removeMgrSn()
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
